package com.tacitknowledge.filters;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

class ClasspathFileReader {
	private Map<String, CacheEntry> cache = new HashMap<String, CacheEntry>();
	private long lastTimeDiskWasAccessed = 0L;
	private long reloadMillis = 0L;

	public File getFile(String fileName) throws FileNotFoundException {
		List<String> classpath = this.getClasspathDirectories();
		String fileSeparator = System.getProperty("file.separator");
		Iterator<String> i = classpath.iterator();

		File file;
		do {
			if (!i.hasNext()) {
				throw new FileNotFoundException("Could not locate file in classpath");
			}

			String directory = (String) i.next();
			if (!directory.endsWith(fileSeparator) && !fileName.startsWith(fileSeparator)) {
				directory = directory + fileSeparator;
			}

			file = new File(directory + fileName);
		} while (!file.exists() || !file.isFile() || !file.canRead());

		this.cache.put(fileName, new CacheEntry(this, file));
		return file;
	}

	public InputStream getResourceAsStream(String fileName) {
		try {
			return new FileInputStream(this.getFile(fileName));
		} catch (FileNotFoundException arg3) {
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
			if (is != null) {
				this.cache.put(fileName, new CacheEntry(this));
			}

			return is;
		}
	}

	public boolean isModified(String fileName) {
		if (this.lastTimeDiskWasAccessed + this.reloadMillis > System.currentTimeMillis()) {
			return false;
		} else {
			this.lastTimeDiskWasAccessed = System.currentTimeMillis();
			CacheEntry cacheEntry = (CacheEntry) this.cache.get(fileName);
			return cacheEntry != null ? cacheEntry.isModified() : true;
		}
	}

	public void setReloadSeconds(int seconds) {
		this.reloadMillis = (long) (seconds * 1000);
	}

	public int getReloadSeconds() {
		return (int) this.reloadMillis / 1000;
	}

	private List<String> getClasspathDirectories() {
		LinkedList<String> directories = new LinkedList<String>();
		String classpath = System.getProperty("java.class.path");
		String separator = System.getProperty("path.separator");
		StringTokenizer st = new StringTokenizer(classpath, separator);

		while (st.hasMoreTokens()) {
			String possibleDir = st.nextToken();
			File file = new File(possibleDir);
			if (file.isDirectory()) {
				directories.add(possibleDir);
			}
		}

		return directories;
	}
}